﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using WebClass;

namespace QuerySelectionLabelingTool
{
    public partial class EvaluateQueries : System.Web.UI.Page
    {
        ExperimentsQueries experimentsQueries;
        List<RadioButtonList> listRadio;
        int existExpeNum;
        int allExpeNum;
        int taskID;
        protected void Page_Load(object sender, EventArgs e)
        {
            ScriptManager1.RegisterAsyncPostBackControl(Button1);
            listRadio = new List<RadioButtonList>();
            experimentsQueries = new ExperimentsQueries();
            taskID = Convert.ToInt32(Request.QueryString["taskID"]);
            Session["currentTaskID"] = taskID;
            experimentsQueries.GetExperimentsQueries((int)(Session["userID"]), taskID,out existExpeNum,out allExpeNum);
            Session["currentNewsID"] = experimentsQueries.News2.ID;
            if (existExpeNum >= 2)
            {
                Button1.Text = "Next";
            }
            else
            {
                Button1.Text = "Done";
            }
            labelIncomplete.Text = (allExpeNum - existExpeNum + 1).ToString() + "/" + allExpeNum.ToString();
            CoverageOperation coverageOpe = new CoverageOperation();
            if (existExpeNum != 0)
            {
                labelTitle.Text = experimentsQueries.News2.title;;
                labelContent.Text = experimentsQueries.News2.newsContent;
                const int columCount = 3;
                int rowIndex = columCount;
                TableRow r = null;
                foreach (QueryControlData item in experimentsQueries.ListQueryControlData)
                {
                    ++rowIndex;
                    if (rowIndex == columCount + 1)
                    {
                        r = new TableRow();
                        tableQueries.Rows.Add(r);
                        rowIndex = 1;
                    }
                    TableCell cell1 = new TableCell();
                    WebQueryControl queryControl = (WebQueryControl)Page.LoadControl("WebQueryControl.ascx");
                    queryControl.QueryText = item.Query;
                    queryControl.QueryLink = coverageOpe.EncodeUrl(item.Query, item.NewsID);
                    queryControl.StateText = CoverageOperation.GetPosition(item.Position);
                    cell1.Controls.Add(queryControl);
                    r.Cells.Add(cell1);

                    RadioButtonList rbl = new RadioButtonList();
                    rbl.RepeatDirection = RepeatDirection.Horizontal;
                    ListItem lItem2 = new ListItem("Good", "0");
                    ListItem lItem3 = new ListItem("Fair", "1");
                    ListItem lItem4 = new ListItem("Bad", "2");
                    rbl.Items.Add(lItem2);
                    rbl.Items.Add(lItem3);
                    rbl.Items.Add(lItem4);

                    TableCell cell2 = new TableCell();
                    
                    cell2.Controls.Add(rbl);
                    cell2.Width = 160;
                    r.Cells.Add(cell2);
                    listRadio.Add(rbl);
                }
            }
            if (existExpeNum == 0)
            {
                Response.Redirect("Default.aspx");
            }
        }
        //save evaluate to database,click "Next Item"
        protected void Button1_Click(object sender, EventArgs e)
        {
            if (existExpeNum > 0)
            {
                string[] inputQueries = textBlockInputQueries.Text.Split(new char[1] { ';' });
                int taskID = Convert.ToInt32(Request.QueryString["taskID"]);
                bool isExistEmpty = false;
                int count2 = 0;
                bool isComplete = true;

                foreach (RadioButtonList rbl in listRadio)
                {
                    rbl.BackColor = System.Drawing.Color.Empty;
                    ++count2;
                    if (rbl.SelectedIndex == -1)
                    {
                        isComplete = false;
                        rbl.BackColor = System.Drawing.Color.LightSalmon;

                    }
                }

                if (isComplete == false)
                {
                    labelMsg.Text = "Please evaluate all queries on this page.";
                    isExistEmpty = true;
                    return;
                }
                List<int> listEvaluate = new List<int>();
                if (isExistEmpty == false)
                {
                    int count = 0;
                    foreach (var item in experimentsQueries.ListQueryControlData)
                    {
                        listEvaluate.Add( Convert.ToInt32(listRadio.ElementAt(count).SelectedValue));
                        ++count;
                    }
                };
                experimentsQueries.SaveEvaluateQuery(listEvaluate);
                if (inputQueries.Count() > 0 && inputQueries[0] != "")
                    experimentsQueries.SaveAppendQuery(inputQueries,listEvaluate);
                if (existExpeNum > 1)
                {
                    Response.Redirect(Request.Url.AbsoluteUri);

                }
                else
                {
                    Response.Redirect("Default.aspx");
                }
            }
            else
            {
                Response.Redirect("Default.aspx");
            }
            
        }

        protected void Button2_Click(object sender, EventArgs e)
        {
            if (this.DropDownList1.Items.Count > 0)
            {
                int selectedTaskID = Convert.ToInt32(this.DropDownList1.SelectedValue);
                int newsID = Convert.ToInt32(Session["currentNewsID"]);

                List<ExistingLabelingResult> listExisting = experimentsQueries.GetNewsQuery(selectedTaskID, newsID);
                int index = 0;
                foreach (QueryControlData item in experimentsQueries.ListQueryControlData)
                {
                    listRadio.ElementAt(index).ClearSelection();
                    ExistingLabelingResult tmp = listExisting.Find(delegate(ExistingLabelingResult eLabel)
                    {
                        if (eLabel.Query == item.Query)
                            return true;
                        return false;
                    });
                    if (tmp != null)
                    {
                        int rank = tmp.Rank;
                        listRadio.ElementAt(index).SelectedIndex = rank;
                        tmp.IsLabeled = true;
                    }
                    ++index;
                }
                this.textBlockInputQueries.Text = "";
                foreach (ExistingLabelingResult eLabeling in listExisting)
                {
                    if (eLabeling.IsLabeled == false && (eLabeling.Rank == 0 || eLabeling.Rank == 1))
                    {
                        this.textBlockInputQueries.Text += eLabeling.Query + ";";
                    }
                }
                if (this.textBlockInputQueries.Text.Length != 0)
                    this.textBlockInputQueries.Text = this.textBlockInputQueries.Text.Substring(0, this.textBlockInputQueries.Text.Length - 1);
            }
        }

        protected void Button3_Click(object sender, EventArgs e)
        {
            Button1_Click(sender, e);
        }
    }
}
